<template>
  <div class="dashboard">
    <div class="class-section">
      <div class="flex justify-between">
        <h2 class="text-gray-600">
          <span class="text-green-500 mr-2 font-bold">|</span>我创建的班级
        </h2>
        <a-button type="primary" @click="createClass"> 创建班级 </a-button>
      </div>
      <a-row :gutter="[24, 24]">
        <a-col v-for="classItem in classes" :key="classItem.id" :span="6">
          <div
            class="border rounded mx-auto m-5 bg-white opacity-90 cursor-pointer"
          >
            <div class="flex p-2 border-b select-none">
              <div
                class="heading text-gray-800 w-full pl-3 font-semibold my-auto"
              >
                {{ mapLevelToCNName(classItem.grade) }}
              </div>
              <div class="buttons ml-auto flex text-gray-600 mr-1">
                <a-popover trigger="click" placement="bottom" arrow="false">
                  <template #content>
                    <div class="flex flex-col">
                      <a
                        @click="
                          () =>
                            showDeleteConfirm(
                              classItem.class_name,
                              classItem.class_no
                            )
                        "
                        class="border-none"
                        >删除班级</a
                      >
                      <a
                        @click="
                          goToClass(classItem.class_no, classItem.class_name)
                        "
                        >班级详情</a
                      >
                    </div>
                  </template>
                  <a class="">
                    <svg
                      t="1732005880919"
                      class="icon"
                      viewBox="0 0 1024 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      p-id="1473"
                      width="16"
                      height="16"
                    >
                      <path
                        d="M415.93 223.79c0-52.98 43.004-95.984 95.984-95.984s95.984 43.004 95.984 95.984-43.004 95.984-95.984 95.984-95.984-43.003-95.984-95.984zM415.93 511.742c0-52.98 43.004-95.984 95.984-95.984s95.984 43.004 95.984 95.984-43.004 95.984-95.984 95.984-95.984-43.004-95.984-95.984zM415.93 799.866c0-52.98 43.004-95.984 95.984-95.984s95.984 43.003 95.984 95.984-43.004 95.983-95.984 95.983-95.984-43.175-95.984-95.983z"
                        p-id="1474"
                      ></path>
                    </svg>
                  </a>
                </a-popover>
              </div>
            </div>
            <div class="overflow-hidden" @click="goToClass(classItem.class_no, classItem.class_name)">
              <div class="shadow-xl flex">
                <div class="each-frame border-box flex-none">
                  <div class="main flex w-full p-8">
                    <div class="sub w-2/6 my-auto">
                      <img
                        src="../../assets/avatar.png"
                        class="rounded-full w-24"
                      />
                    </div>
                    <div class="ml-12 my-auto">
                      <div class="text-md font-bold mb-4">
                        {{ classItem.class_name }}
                      </div>
                      <div class="text-xl font-bold mt-2">
                        {{ classItem.studentCount }}人
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div
            @click="createClass"
            style="height: 10.4rem"
            class="cursor-pointer border-2 rounded mx-auto m-5 bg-white opacity-90 flex justify-center items-center"
          >
            <div class="overflow-hidden">
              <div class="shadow-xl flex">
                <div class="flex items-center">
                  <PlusOutlined class="icon" />创建班级
                </div>
              </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, h } from "vue";

import { useRouter } from "vue-router";
import { Modal, message } from "ant-design-vue";
import { mapLevelToCNName } from "@/utils/mapLevel";
import { useClassStore } from "@/stores/class";
const classes = ref([]);
const router = useRouter();
const loading = ref(false);
const classStore = useClassStore();
const deleteClass = async (classNo) => {
  try {
    const response = await window.electronAPI.deleteClassData(classNo);
    if (response.success) {
      message.success("班级已成功删除");
      await loadClasses();

      if (classStore.selectedClass && classStore.selectedClass.class_no === classNo) {
        if (classes.value.length > 0) {
          classStore.selectClass(classes.value[0]);
          message.info(`已自动选择班级：${classes.value[0].class_name}`);
        } else {
          classStore.clearClass();
        }
      }
    } else {
      message.error("删除班级失败，请重试: " + response.error);
    }
  } catch (error) {
    message.error("删除班级失败，请重试: " + error.message);
  }
};

const createClass = () => {
  router.push({ path: "/createclass" });
};
const getClassStudentCount = async (classNo) => {
  try {
    const response = await window.electronAPI.getClassStudentCount(classNo);
    if (response.success) {
      return response.count;
    } else {
      message.error("获取班级学生人数失败: " + response.error);
      return 0;
    }
  } catch (error) {
    message.error("获取班级学生人数失败: " + error.message);
    return 0;
  }
};
const loadClasses = async () => {
  loading.value = true;
  try {
    const data = await window.electronAPI.getClassData();
    if (data.success) {
      classes.value = data.classes;
    } else {
      classes.value = [];
      message.error("加载班级数据失败: " + data.error);
    }
  } catch (error) {
    console.error("加载班级数据失败:", error);
    classes.value = [];
    message.error("加载班级数据失败: " + error.message);
  }
  loading.value = false;
};
const showDeleteConfirm = async (className, classNo) => {
  const studentCount = await getClassStudentCount(classNo);

  Modal.confirm({
    title: "删除班级",
    content:
      studentCount > 0
        ? `该班级下有 ${studentCount} 名学生，是否确认删除？`
        : `确认删除？`,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await deleteClass(classNo);
    },
    zIndex: "9999",
  });
};
const goToClass = (classNo, className) => {
  router.push({
    path: `/class/${classNo}/${className}`,
  });
};
onMounted(() => {
  loadClasses();
});
</script>

<style scoped lang="less">
.dashboard {
  padding: 10px;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.class-section {
  margin-top: 10px;
  padding: 10px;
  flex: 1;
  overflow-y: auto;
}
.class-section h2 {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}
</style>
